<template>
  <div class="webchatApp">
    <configCompositionTwoWindowStyle>
      <template slot="card">
        <div class="base-content">
          <search :isShowInput="false"
                  :isReloadIvr="false"
                  :showAdvSearch="false"
                  :showAdd="wechatType === 'wechatAppAccess' || wechatType === 'wechatMiniApp'"
                  @add="add"
                  @refresh="refresh"
                  @turnPage="turnPage"
                  :currentPage="currentPage"
                  :count="count"
                  :pageSize="10">
            <el-radio-group v-model="wechatType" class="base-content-radio" @change="radioChange">
              <el-radio label="wechatMiniApp">{{$t('config.channel.wechatMiniApp')}}</el-radio>
              <el-radio label="wechatAppAccess">{{$t('config.channel.wechatApp')}}</el-radio>
              <el-radio label="wechatAppH5">{{$t('config.channel.wechatAppH5')}}</el-radio>
            </el-radio-group>
          </search>
          <el-table highlight-current-row :data="tableData" stripe v-show="wechatType === 'wechatMiniApp'" size="mini">
            <el-table-column prop="nick_name" :label="$t('configLazyLoad.channel.appletName')">
            </el-table-column>
            <el-table-column prop="to_peer_name" :label="$t('public.queues')">
            </el-table-column>
            <el-table-column prop="robotname" :label="$t('configTabTitle.isUseRobt2')">
            </el-table-column>
            <el-table-column prop="last_update_time" :label="$t('monitor.updateTime')">
            </el-table-column>
            <el-table-column :label="$t('public.operate')">
              <template scope="scope">
                <el-button @click="editWechatMini(scope.row, 'wechatMiniApp')" type="text" size="small" class="update">{{$t('public.edit')}}</el-button>
                <el-button type="text" @click="deleteWechatMini(scope.row, 'wechatMiniApp')" size="small" class="del">{{$t('public.delete')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table highlight-current-row :data="tableData" stripe v-show="wechatType === 'wechatAppAccess'" size="mini">
            <el-table-column prop="name" :label="$t('configLazyLoad.channel.appletName')">
            </el-table-column>
            <el-table-column prop="to_peer_name" :label="$t('public.queues')">
            </el-table-column>
            <el-table-column prop="robotname" :label="$t('configTabTitle.isUseRobt2')">
            </el-table-column>
            <el-table-column prop="last_update_time" :label="$t('monitor.updateTime')">
            </el-table-column>
            <el-table-column :label="$t('public.operate')">
              <template scope="scope">
                <el-button @click="editWechatMini(scope.row, 'wechatApp')" type="text" size="small" class="update">{{$t('public.edit')}}</el-button>
                <el-button type="text" @click="deleteWechatMini(scope.row, 'wechatApp')" size="small" class="del">{{$t('public.delete')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table highlight-current-row :data="tableData" stripe v-show="wechatType === 'wechatAppH5'" size="mini">
            <el-table-column prop="displayName" :label="$t('configLazyLoad.channel.appletName')" width="">
            </el-table-column>
            <el-table-column prop="fileName" :label="$t('configLazyLoad.channel.wexinAPPTip3')">
            </el-table-column>
            <el-table-column  :label="$t('public.operate')" width="180">
              <template scope="scope">
                <el-button type="text" size="small" @click="editWeixinPro(scope.row)">{{$t('sms.searchToLook')}}</el-button>
                <el-button type="text" size="small" class="del" @click="delWeixinPro(scope.row)">{{$t('public.delete')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template slot="detail">
        <BreadCrumbConfig v-if="isShowAddOrEdit || isShowH5 || isShowWebchatMini" :titleArr="titleArr" @back="cancle"></BreadCrumbConfig>
        <webchatAppEdit v-if="isShowAddOrEdit && activeHandel === 'edit'" @submitEditOrAdd="submitEditOrAdd" :wechatConfigData="wechatConfigData"></webchatAppEdit>
        <webchatAppAdd v-if="isShowAddOrEdit && activeHandel === 'add'" @submitEditOrAdd="submitEditOrAdd" :wechatUrl="wechatUrl" @addWechaH5="addWechaH5" @cancle="cancle"></webchatAppAdd>
        <webchatH5Add v-if="isShowH5" :isAddOrEdit="isH5AddOrEdit" :weixinH5Form="weixinForm" @refresh="refresh" @resetFields="resetFields"></webchatH5Add>
        <webchatMiniIndex v-if="isShowWebchatMini" @weixinMiniSave="weixinMiniSave" :wechatConfigData="wechatConfigData" :weixinMiniShowType="weixinMiniShowType"></webchatMiniIndex>
      </template>
    </configCompositionTwoWindowStyle>
    <el-dialog :title="$t('configLazyLoad.channel.wexinAPPTip4')" :visible.sync="dialogIsShow" width="80%" @close="closeDialog">
      <div style="height: 500px">
        <iframe :src="wechatMiniUrl" frameborder="0" style="overflow: scroll;width: 100%;height: 100%"></iframe>
      </div>
    </el-dialog>
    <el-dialog :title="$t('public.tip')" :visible.sync="isAddShow" width="30%">
      <span style="padding-left: 10px">{{$t('webchat.weixinminiMangeError')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddShow = false" size="mini">{{$t('webchat.cancel')}}</el-button>
        <el-button type="primary" size="mini" @click="isAddShowTrueFun">{{$t('webchat.determine')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import Agent from '@/components/public-modules/cache/Agent'
  import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/BreadCrumbConfig'
  import webchatAppEdit from './webchatAppEdit.vue'
  import webchatAppAdd from './webchatAppAdd.vue'
  import webchatH5Add from './webchatH5Add.vue'
  import webchatMiniIndex from './webchatMiniIndex.vue'
  import configCompositionTwoWindowStyle from '../../../../ui-modules/config/configCompositionTwoWindowStyle'
  import search from '../base/search.vue'
  import { getCacheByKey } from '@/utils/m7Utils.js'
//  import wechatModify from './wechatModify.vue'
  export default {
    name: 'webChatAppManage',
    data () {
      return {
        titleArr: [this.$t('configLazyLoad.channel.wexinAPPTip5'), this.$t('public.add')],
        tableData: [],
        isShowAddOrEdit: false,   //   右侧  新建或修改 显隐
        isShowH5: false,   //   右侧  新建或修改 显隐
        activeHandel: 'add',  // 右侧显示的模块
        isH5AddOrEdit: 'add',  // 右侧显示的模块
        wechatType: 'wechatMiniApp',
        wechatMiniUrl: '',
        weixinMiniShowType: 'add',
        currentPage: 1,
//        pageSize: 0,
        count: 0,
        wechatUrl: '',
        wechatConfigData: {},
        weixinForm: {
          displayName: '',
          file: '',
          _id: ''
        },
        preweixinList: '',
        dialogIsShow: false,
        isShowWebchatMini: false,
        isAddShow: false
      }
    },
    watch: {
      wechatType () {
        this.currentPage = 1
        this.cancle()
        this.fetchData()
      }
    },
    methods: {
      isAddShowTrueFun () {
        this.isAddShow = false
        this.isShowWebchatMini = false
      },
      cancle () {
        this.isShowAddOrEdit = false
        this.isShowH5 = false
        if (this.wechatType === 'wechatMiniApp') {
          if (this.isShowWebchatMini && !('to_peer' in this.wechatConfigData)) {
            this.isAddShow = true
          } else {
            this.isShowWebchatMini = false
          }
          // this.fetchData()
        }
      },
      add () {
        if (this.wechatType === 'wechatAppAccess') {
          this.isShowH5 = false
          this.isShowAddOrEdit = true
          this.activeHandel = 'add'
          this.titleArr = [this.$t('config.channel.wechatApp'), this.$t('public.add')]
        } else if (this.wechatType === 'wechatMiniApp') {
          this.titleArr = [this.$t('configLazyLoad.channel.wexinAPPTip4'), this.$t('public.add')]
          this.dialogIsShow = true
          let accountId = this.$store.state.session.user.account
          let account = this.$store.state.session.account
          this.$store.dispatch('getWeixinMiniAuthConfigList', {}).then((resp) => {
            if (resp.success) {
              this.preweixinList = resp.list
              this.wechatMiniUrl = resp.wechatUrl.replace('http://', '//') + '/?action=getWxminiPreAuthCode&account=' + accountId + '&appId=' + (account.wechatAppId || '')
            }
          })
        }
      },
      closeDialog () {
        this.wechatMiniUrl = ''
      },
      refresh () {
        this.currentPage = 1
        this.fetchData()
      },
      submitEditOrAdd () {
        this.isShowAddOrEdit = false
        this.fetchData()
      },
      addWechaH5 () {
        this.titleArr = [this.$t('config.channel.wechatAppH5'), this.$t('public.add')]
        this.isShowH5 = true
        this.isShowAddOrEdit = false
        this.isH5AddOrEdit = 'add'
      },
      turnPage (val) {
        this.currentPage = val
        this.fetchData()
      },
      fetchData () {
        this.tableData = []
        if (this.wechatType === 'wechatAppH5') {
          let page = this.currentPage || 1
          let data = {'page': page, 'limit': 10}
          this.$store.dispatch('getWeixinMiniAppCheckFileList', data).then((resp) => {
            if (resp && resp.success) {
              this.count = resp.count
              this.tableData = resp.data || []
            }
          })
        } else {
          let actionName = ''
          let page = this.currentPage || 1
          let data = {'page': page, 'limit': 10}
          if (this.wechatType === 'wechatAppAccess') {
            actionName = 'queryWxMiniConfigArr'
          } else if (this.wechatType === 'wechatMiniApp') {
            actionName = 'getWeixinMiniAuthConfigList'
          }
          this.$store.dispatch(actionName, data).then((resp) => {
            if (resp) {
              this.wechatUrl = resp.wechatUrl
              this.count = resp.count
              let p1 = this.$store.dispatch('getCache', {type: 'mailQueues'})
              let p2 = this.$store.dispatch('getCache', {type: 'robotConfig'})
              let p3 = this.$store.dispatch('queryM7AIRobot', {})
              Promise.all([p1, p2, p3]).then(([a, b, c]) => {
                let totalRobot = []
                let m7Robot = b || []
                let aiRobots = []
                if (c.success && c.data && c.data.length > 0) {
                  aiRobots = c.data
                  aiRobots.forEach((item) => {
                    item._id = item.Id
                    item.robot_type = item.Nick
                  })
                }
                totalRobot = m7Robot.concat(aiRobots)
                resp.list && resp.list.length > 0 && resp.list.forEach((item, index) => {
                  let peer = getCacheByKey('mailQueues', 'Exten', item.to_peer)
                  if (peer) {
                    resp.list[index]['to_peer_name'] = peer.DisplayName
                  }
                  if (item.robot) {
                    if (totalRobot.length > 0) {
                      let robot = totalRobot.find((robot1) => { return robot1._id === item.robot })
                      if (robot) {
                        resp.list[index]['robotname'] = robot.robot_type
                      } else {
                        resp.list[index]['robotname'] = ''
                      }
                    }
                  } else {
                    resp.list[index]['robotname'] = this.$t('config.channel.noUsed')
                  }
                })
                this.tableData = resp.list
              })
            }
          })
        }
      },
      resetFields () {
        this.weixinForm.displayName = ''
        this.weixinForm.file = ''
      },
      editWeixinPro (row) {
        this.weixinForm._id = row._id
        if (this.$refs['weixinForm']) {
          this.$refs['weixinForm'].resetFields() // 表单重置
        }
        this.$store.dispatch('getWeixinMiniAppCheckFile', {'_id': row._id}).then((resp) => {
          if (resp.success) {
            this.isShowH5 = true
            this.titleArr = [this.$t('config.channel.wechatAppH5'), this.$t('sms.searchToLook')]
            this.isShowAddOrEdit = false
            this.isH5AddOrEdit = 'edit'
            this.weixinForm.displayName = resp.data.displayName || ''
            this.weixinForm.file = resp.data.fileName || ''
            this.isSmsTempEditShow = true
          }
        })
      },
      delWeixinPro (row) {
        let data = {'_id': row._id}
        this.$confirm(this.$t('config.channel.warnDelWeixinPro'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('delWeixinMiniAppCheckFile', data).then((resp) => {
            if (resp && resp.success) {
              this.fetchData()
              this.$message({
                message: this.$t('config.channel.deleteSuccess'),
                type: 'success'
              })
            } else {
              this.$message({
                message: this.$t('config.channel.deleteFailure'),
                type: 'error'
              })
            }
          })
        }).catch(() => {
          console.log('取消')
        })
      },
      editWechatMini (row, type) {
        if (type === 'wechatApp') {
          this.$store.dispatch('queryWeixinConfigById', {_id: row._id}).then((resp) => {
            if (resp.success) {
              this.activeHandel = 'edit'
              this.titleArr = [this.$t('configLazyLoad.channel.wexinAPPTip5'), this.$t('public.edit')]
              this.isShowAddOrEdit = true
              this.isShowH5 = false
              this.wechatConfigData = resp.data
            }
          })
        } else if (type === 'wechatMiniApp') {
          this.$store.dispatch('getWeixinMiniAuthConfigById', {_id: row._id}).then((res) => {
            if (res && res.success) {
              this.titleArr = [this.$t('configLazyLoad.channel.wexinAPPTip6'), this.$t('public.edit')]
              this.wechatConfigData = row
              this.isShowWebchatMini = true
              this.wechatConfigData = res.row
              this.weixinMiniShowType = 'edit'
            }
          })
        }
      },
      deleteWechatMini (row, type) {
        let actionName = ''
        if (type === 'wechatApp') {
          actionName = 'deleteWxMiniConfig'
        } else if (type === 'wechatMiniApp') {
          actionName = 'delWeixinMiniAuthConfig'
        }
        this.$confirm(this.$t('configLazyLoad.channel.wexinAPPTip7'), this.$t('public.delete'), {
          confirmButtonText: this.$t('public.delete'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch(actionName, {_id: row._id}).then((req) => {
            if (req.success) {
              this.$message.success(this.$t('configLazyLoad.public.deleteSuccess'))
              this.fetchData()
              this.isShowWebchatMini = false
            }
          })
        })
      },
      getMessageFromChild (d) {
        if (d.data === 1) {
          this.$message.success(this.$t('configLazyLoad.channel.wexinAPPTip8'))
          this.dialogIsShow = false
          this.successAfter()
        } else if (d.data === 2) {
          this.$message.error(this.$t('configLazyLoad.channel.wexinAPPTip9'))
          this.dialogIsShow = false
        } else if (d.data === 3) {
          this.$message.error(this.$t('configLazyLoad.channel.wexinAPPTip10'))
          this.dialogIsShow = false
        } else if (d.data === 4) {
          this.$message.error(this.$t('configLazyLoad.channel.wexinAPPTip11'))
          this.dialogIsShow = false
        }
      },
      successAfter () {
        // 通过扫码前后数组对比，判断是否是新增的微信号 还是已有的微信号
        this.$store.dispatch('getWeixinMiniAuthConfigList', {}).then((resp) => {
          if (resp.success) {
            let preArray = []
            this.preweixinList.forEach((item) => {
              preArray.push(item._id)
            })
            let newWeixin = resp.list.filter((item) => {
              return preArray.indexOf(item._id) === -1
            })
            this.isShowWebchatMini = true
            // this.newWeixin = newWeixin[0]
            this.wechatConfigData = newWeixin[0]
          }
        })
      },
      radioChange () {
        this.isShowWebchatMini = false
        // this.fetchData()
      },
      weixinMiniSave () {
        this.fetchData()
        this.isShowWebchatMini = false
      }
    },
    components: {
      configCompositionTwoWindowStyle,
      BreadCrumbConfig,
      webchatAppEdit,
      webchatAppAdd,
      webchatH5Add,
      webchatMiniIndex,
      search,
      Agent
    },
    mounted () {
      this.fetchData()
      if (window.addEventListener) {
        window.addEventListener('message', this.getMessageFromChild)
      } else {
        window.attachEvent('onmessage', this.getMessageFromChild)
      }
    },
    beforeDestroy () {
      window.removeEventListener('message', this.getMessageFromChild)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .new-config
    .base-content
      height: calc(100vh - 54px)
  .base-content
    height: calc(100vh - 170px)
    overflow-y: auto
  .update
    cursor pointer
  .el-table .cell >.el-button--text.del
    color $c-pink
    cursor pointer
  .webchatApp
    overflow auto
</style>
<style lang="stylus">
  .base-content-radio
    .el-radio + .el-radio
      margin-left 0px
    .el-radio
      margin-right 0px
</style>




















